package com.example.mykotilin.livedata

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

class LiveDataViewModel(private val dataSource: DataSource) : ViewModel() {
    val currentTime = dataSource.getCurrentTime()
    val currentTimeTransformed = currentTime.switchMap {
        liveData {
            emit(timeStampToTime(it))
        }
    }
    val currentWeather: LiveData<String> = liveData {
        emit(LOADING_STRING)
        emitSource(dataSource.fetchWeather())
    }
    val cachedValue = dataSource.cachedData
    fun onRefresh() {
        viewModelScope.launch {
            dataSource.fetchNewData()
        }
    }
    private suspend fun timeStampToTime(timestamp: Long): String {
        delay(500)
        val date = Date(timestamp);
        return date.toString()
    }
    companion object {
        const val LOADING_STRING = "Loading..."
    }
}

object LiveDataVMFactory : ViewModelProvider.Factory {
    private val dataSource = DefaultDataSource(Dispatchers.IO)
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        @Suppress("UNCHECKED_CAST")
        return LiveDataViewModel(dataSource) as T
    }

}